package com.itheima.controller;

import com.itheima.aspect.Log;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("clazzs")
@Scope("prototype")
public class ClazzController {
    @Autowired
    ClazzService clazzService;


    /**
     * 查询所有班级
     * @return
     */
    @GetMapping
    public Result getAllClazz(EmpQueryParam cqp){
        PageBean pageBean =  clazzService.getAllClazz(cqp);
        return Result.success(pageBean);
    }



    /**
     * 新增班级
     */
    @PostMapping
    @Log
    public Result addClazz(@RequestBody Clazz clazz){
        clazzService.addClazz(clazz);
        return Result.success();
    }


    /**
     * 根据id查询班级（单个）
     */
    @GetMapping("/{id}")
    public Result getClazz(@PathVariable(("id")) Integer id){
        Clazz clazz =  clazzService.getClazz(id);
        return Result.success(clazz);
    }

    @GetMapping("/name")
    public Result getClazzByName(String name)  {
        Clazz clazz =  clazzService.getClazzByName(name);
        return Result.success(clazz);
    }

    /**
     * 修改班级信息
     * @param clazz
     * @return
     */
    @PutMapping
    @Log
    public Result modifyClazz(@RequestBody Clazz clazz){
        clazzService.modifyClazz(clazz);
        return Result.success();
    }


    /**
     * 根据id删除班级信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Log
    public Result deleteClazz(@PathVariable Integer id){
        clazzService.deleteClazz(id);
        Clazz clazz = clazzService.getClazz(id);
        //删除之后再根据这个id来调用查询方法，如果查询结果不为null，则说明未删除该班级，，输出error，否则success
        if (clazz != null){
            return Result.error("对不起, 该班级下有学生, 不能直接删除");
        }else {
            return Result.success();
        }
    }

    /**
     * 新增班级中的查询班级接口
     * @return
     */
    @GetMapping("/list")
    public Result getAllClazz(){
        List<Clazz> clazzList = clazzService.getClazzs();
        return Result.success(clazzList);
    }

}
